/* Exercise 5.33
   ejer5_33.c */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* Function prototipes */
int getNumber( void );

/* function main begins program execution */
int main( void )
{
    int number, input, guesses;
    char resp;

    srand( time( NULL ));
    do
    {
        number = getNumber();

        printf( "I have a number between 1 and 1000\nCan you guess the number?\nPlease type your first guess " );
        scanf( "%d", &input );
        guesses = 1;

        while ( input != number )
        {
            if ( input < number )
                printf( "Too low. Try again. ");
            else
                printf( "Too high. Try again. ");
            scanf( "%d", &input );
            ++guesses;
        }

        /* A person should be able to guess the number in 10 or minus guesses because                       *
         * if we use the binary search algorithm, then the maximum number of guesses is 10 because          *
         * 1024 (aproximatly to 1000) is 2^10, the binary search says that a search must be x where x is:   *
         *  2^x = numberofelements                                                                          */
        if ( guesses < 10 )
            printf( "Either you know the secret or you got lucky!\n");
        else
            if ( guesses > 10 )
                printf( "You should be able to do better!\n");
            else
                printf( "Ahah! You know the secret!\n" );

        printf ("Would you like to play again (y or n)? ");
        resp = getchar();

        while ( resp == '\n' || resp == '\t' || resp == ' ' )
            resp = getchar();
    } while ( resp != 'n' && resp != 'N' );

	return 0; /* indicate that program ended successfully */
} /* end function main */

/* This function returns a random number between 1 and 1000 */
int getNumber( void )
{
    return rand() % 1000 + 1;
}
